﻿using System;
using System.Linq;
using Business_Layer.Business_Layer.Procesos;
using Business_Layer.Data_Access_Layer;

namespace SAP.User_Interface.Login
{
    public partial class Login : System.Web.UI.Page
    {
        readonly DB_SAPDataContext _dbSap = new DB_SAPDataContext();
        private VariablesPrivadas _vpSession;
        private string _action = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _vpSession = new VariablesPrivadas(Session);

            _action = Request.Form["action"];

            if (!string.IsNullOrWhiteSpace(_action))
                GetType().GetMethod(_action).Invoke(this, null);
        }

        public void Autenticar()
        {
            
            var username = Request.Form["username"];
            var userpassword = Request.Form["userpassword"];

            var getUser =
                _dbSap.USUARIOS.FirstOrDefault(
                    x => x.USUARIO_nombreUsuario.Equals(username) && x.USUARIO_password.Equals(userpassword));

            if (getUser != null)
            {
                _vpSession.UserName = username;
                _vpSession.UserRol = userpassword;
                var integrante = getUser.INTEGRANTES.FirstOrDefault();
                if (integrante != null)
                    _vpSession.UserId = integrante.INTEGRANTES_ID;
                var integrantes = getUser.INTEGRANTES.FirstOrDefault();
                if (integrantes != null)
                    _vpSession.UserRol = integrantes.ROLESPROYECTO.ROLPROYECTO_nombre;
                Response.Write("logged");
            }

            else
                Response.Write("aborted");
            
            Response.End();
        }

        public void FinalizarSesion()
        {
            _vpSession = new VariablesPrivadas(Session);
            Session.Abandon();
            Response.Write("loggedOut");
            Response.End();
        }
    }
}